﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ConfigSource.cs" company="">
//   
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace AdminTool
{
    using System;
    using System.Threading.Tasks;
    using System.Windows.Forms;

    using ExecutionTool.CopyDatabase;
    using ExecutionTool.Profile;

    public partial class ConfigSource : UserControl, IProfileConfigurator
    {
        #region Constructors and Destructors

        public ConfigSource()
        {
            this.InitializeComponent();
        }

        #endregion

        #region Public Methods and Operators

        public void LoadProfile(Profile profile)
        {
            this.textBoxServerNamePrefix.Text = profile.Source.ServerNamePrefix;
            this.textBoxUsername.Text = profile.Source.UserName;
            this.textBoxPassword.Text = profile.Source.Password;
            this.textBoxDatabaseName.Text = profile.Source.DatabaseName;

            this.ResetMessage();
            this.WriterMessage("Profile data loaded.");
        }

        public void SaveProfile(Profile profile)
        {
            profile.Source.ServerNamePrefix = this.textBoxServerNamePrefix.Text.Trim();
            profile.Source.UserName = this.textBoxUsername.Text.Trim();
            profile.Source.Password = this.textBoxPassword.Text.Trim();
            profile.Source.DatabaseName = this.textBoxDatabaseName.Text.Trim();

            this.WriterMessage("Profile data saved.");
        }

        #endregion

        #region Methods

        private void ResetMessage()
        {
            this.textBoxDetectedDatabaseName.Text = string.Empty;
        }

        private void WriterMessage(string message)
        {
            this.textBoxDetectedDatabaseName.Text += message;
            this.textBoxDetectedDatabaseName.Text += Environment.NewLine;
        }

        private void buttonTestConnection_Click(object sender, EventArgs e)
        {
            var serverName = this.textBoxServerNamePrefix.Text.Trim();
            var userName = this.textBoxUsername.Text.Trim();
            var password = this.textBoxPassword.Text.Trim();
            var databaseName = this.textBoxDatabaseName.Text.Trim();

            var error = false;

            if (string.IsNullOrWhiteSpace(serverName))
            {
                this.WriterMessage("Please specify the server name prefix first.");
                error = true;
            }

            if (string.IsNullOrWhiteSpace(userName))
            {
                this.WriterMessage("Please specify the user name first.");
                error = true;
            }

            if (string.IsNullOrWhiteSpace(password))
            {
                this.WriterMessage("Please specify the password first.");
                error = true;
            }

            if (error)
            {
                return;
            }

            this.textBoxDetectedDatabaseName.Text = string.Empty;
            this.WriterMessage("Starting to test the location...");
            var adapter = new SqlAzureAdapter();

            if (!string.IsNullOrWhiteSpace(databaseName))
            {
                Task.Factory.StartNew(
                    () =>
                    adapter.TestConnection(
                        new SqlAzureLocation { ServerNamePrefix = serverName, UserName = userName, Password = password, DatabaseName = databaseName }))
                    .ContinueWith(
                        t =>
                            {
                                if (t.IsFaulted && t.Exception != null)
                                {
                                    this.WriterMessage("Test failed. -->" + t.Exception);
                                }
                                else
                                {
                                    this.WriterMessage("Tested successfully.");
                                }
                            });
            }

            Task.Factory.StartNew(
                () =>
                adapter.GetExistingDatabaseNames(new SqlAzureLocation { ServerNamePrefix = serverName, UserName = userName, Password = password })).
                ContinueWith(
                    t =>
                        {
                            if (t.IsFaulted && t.Exception != null)
                            {
                                this.WriterMessage("Failed to get existing database names. -->" + t.Exception);
                            }
                            else
                            {
                                if (t.Result.Count > 0)
                                {
                                    this.WriterMessage("Existing databases:");

                                    foreach (var name in t.Result)
                                    {
                                        this.WriterMessage("\t" + name);
                                    }
                                }
                            }
                        });
        }

        private void checkBoxTogglePassword_CheckedChanged(object sender, EventArgs e)
        {
            var cb = (CheckBox)sender;
            this.textBoxPassword.UseSystemPasswordChar = !cb.Checked;

            ////if (cb.Checked)
            ////{
            ////    cb.Text = "Hide clear text";
            ////}
            ////else
            ////{
            ////    cb.Text = "Show clear text";
            ////}
        }

        #endregion
    }
}
